﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;


namespace Microsoft.Extensions.DependencyInjection
{
    public static class JsonConvertExtensions
    {
        /// <summary>
        /// 主要用于解决长整型数据序列化成json时因精度导致异常的问题，会自动序列化为字符型
        /// </summary>
        /// <param name="builder"></param>
        public static void AddJsonConverter(this IMvcBuilder builder)
        {
            builder.AddNewtonsoftJson(opt =>
            {
                opt.SerializerSettings.DateFormatString = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
                opt.SerializerSettings.ContractResolver = new CustomContractResolver();
            });
        }
    }

    public class CustomContractResolver : CamelCasePropertyNamesContractResolver
    {
        protected override JsonConverter ResolveContractConverter(Type objectType)
        {

            if (objectType == typeof(long))
                return new JsonConverterLong();
            return base.ResolveContractConverter(objectType);
        }
    }

    public class JsonConverterLong : JsonConverter
    {

        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if ((reader.ValueType == null || reader.ValueType == typeof(long?)) && reader.Value == null)
            {
                return null;
            }
            else
            {
                long.TryParse(reader.Value != null ? reader.Value.ToString() : "", out long value);
                return value;
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {

            if (value == null)
                writer.WriteValue(value);
            else
                writer.WriteValue(value.ToString());
        }
    }
}
